//
//  JKMeFooterView.m
//  Baisi
//
//  Created by albert on 16/3/29.
//  Copyright (c) 2016年 albert. All rights reserved.
//

#import "JKMeFooterView.h"
#import "JKSquareModel.h"
#import "MJExtension.h"
#import "JKSquareButton.h"
#import "JKWebViewController.h"

@implementation JKMeFooterView
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
    }
    return self;
}

//创建方块
- (void)createSquares:(NSArray *)squaress{
    
    NSArray *squares = [JKSquareModel mj_objectArrayWithKeyValuesArray:squaress];
    
    NSInteger count = squares.count;
    //一行最多4列
    NSInteger maxCols = 4;
    
    //宽度和高度
    CGFloat buttonW = JKScreenW / maxCols;
    CGFloat buttonH = buttonW;
    
    for (NSInteger i = 0; i < count; i++) {
        
        if (![squares[i] isKindOfClass:[JKSquareModel class]]) {
            
            count--;
            i--;
            
            continue;
        }
        
        NSInteger row = i / maxCols;
        NSInteger col = i % maxCols;
        
        //创建button。按钮超出父控件范围的话是无法点击的
        JKSquareButton *button = [JKSquareButton buttonWithType:(UIButtonTypeCustom)];
        
        //添加点击事件
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
        
        [self addSubview:button];
        
        //直接给每一个button来一个模型
        button.square = squares[i];
        
        //计算frame
        CGFloat buttonX = col * buttonW;
        CGFloat buttonY = row * buttonH;
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
        
        //获取按钮的最大Y值，来确定高度，比较简单
        //self.height = CGRectGetMaxY(button.frame);
    }
    
    //总行数
//    NSUInteger rows = squares.count / maxCols;
//    if (squares.count % maxCols) {
//        rows++;
//    }
    
    //总行数 == (总个数 + 每行最多列数 - 1) / 每行最多列数
    NSUInteger rows = (count + maxCols - 1) / maxCols;
    
    //计算footerView高度
    self.height = rows * buttonH;
    
    //重绘，背景图片才会显示
    //[self setNeedsDisplay];
}

//点击button
- (void)buttonClick:(JKSquareButton *)button{
    
    //不是网页，直接返回，有其它操作的话再说
    if (![button.square.url hasPrefix:@"http"]) return;
    
    //创建网页的控制器
    JKWebViewController *webVc = [[JKWebViewController alloc] init];
    //设置标题
    webVc.title = button.square.name;
    //传递模型数据
    webVc.urlStr = button.square.url;
    
    //取出根控制器UITabBarController
    UITabBarController *tabBarVc = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    
    //取得UITabBarController选中的控制器
    UINavigationController *nav = (UINavigationController *)tabBarVc.selectedViewController;
    
    //push
    [nav pushViewController:webVc animated:YES];
}

//因为view没有背景图片之类的，所以直接找一张图片画上去
//- (void)drawRect:(CGRect)rect{
//    [[UIImage imageNamed:@"mainCellBackground"] drawInRect:rect];
//}
@end
